import json
import random

from django.shortcuts import render
from app01.models import *
from django.views import View
from django.http import JsonResponse

from web.models import CollectMuseum


# Create your views here.


class index(View):
    def get(self, request, *args, **kwargs):
        # 获取数据库中所有记录
        provinces = MuseumName.objects.values('province').distinct()
        museums_obj = MuseumName.objects.all()
        museums_data = list(museums_obj.values())  # 将QuerySet转换为列表
        record_count = museums_obj.count()

        min_id = AntiqueInfo.objects.all().order_by('id').first().id
        antique = AntiqueInfo.objects.filter(id__exact=min_id)
        antique_data = list(antique.values())
        return render(request, 'index.html',
                      {'museums_obj': json.dumps(museums_data), 'provinces': provinces, 'record_count': record_count,
                       'antique': antique_data})


class info(View):
    def get(self, request, *args, **kwargs):
        museum = str(kwargs.get('museum'))
        museums_obj = MuseumInfo.objects.filter(name=museum)
        if museums_obj:
            sid = museums_obj[0].id
        else:
            sid = -1
        uid = request.session['user_id']  # session中提取当前登录的用户
        fav_list = CollectMuseum.objects.filter(who_clt_id=uid)  # 找出所有该用户的收藏
        if fav_list.filter(clt_relation_museum_id=sid):  # 检查有没有该小说id
            fs = 1  # 已收藏
        else:
            fs = 0  # 未收藏
        return render(request, 'info.html', {'museums_obj': museums_obj, 'fav_status': fs, 'id': sid})


def get_province_data(request, province):
    museums_obj = MuseumName.objects.filter(province=province)
    record_count = museums_obj.count()

    museums_data = list(museums_obj.values())  # 转换为字典形式的数据
    museums_json = json.dumps(museums_data)

    return JsonResponse({'museums_obj': museums_json, 'province': province, 'record_count': record_count},
                        content_type="application/json")


def search(request, search_value):
    # search_value = request.POST.get('searchValue')
    print(search_value)
    # 进行搜索操作
    museums_obj = MuseumName.objects.filter(name__icontains=search_value)
    record_count = museums_obj.count()
    museums_data = list(museums_obj.values())  # 转换为字典形式的数据
    museums_json = json.dumps(museums_data)
    # 返回搜索结果

    return JsonResponse({'museums_obj': museums_json, 'record_count': record_count}, content_type="application/json")


def update_antique(request, antique_id):
    # Retrieve the AntiqueInfo objects based on the given conditions
    antique = AntiqueInfo.objects.filter(id__exact=antique_id)
    antique_data = list(antique.values())
    antique_json = json.dumps(antique_data)

    return JsonResponse({'antique': antique_json}, content_type="application/json")
